package net.chrisrichardson.ec2deployer.applications

import groovy.mock.interceptor.MockFor
import net.chrisrichardson.ec2deployer.core.EC2Server
import net.chrisrichardson.ec2deployer.cluster.DatabaseTier
import net.chrisrichardson.ec2deployer.cluster.TerracottaTier
import net.chrisrichardson.ec2deployer.cluster.WebServerTier
import net.chrisrichardson.ec2deployer.util.FileBasedTemplate

class SpringSourceDmServerTest extends AbstractApplicationServerTestCase {

    String expectedServerDotXml = "expectedServletContainerConfig"

    public void testStart() {

        mockFileBasedTemplate = new MockFor(FileBasedTemplate)

        mockFileBasedTemplate.demand.process {name, params ->
            assertEquals "/templates/springSourceApplicationPlatform/servletContainer.config", name
            assertEquals(['jvmRoute': "tomcat0"], params)
            expectedServerDotXml
        }

        mockTomcatEC2Server.demand.isRunning {true}

        mockTomcatEC2Server.demand.ssh {cmd, input ->
            assertEquals "cat > .sapenv", cmd
            assertEquals """
export JAVA_OPTS=' -Dfoo=myPrivateDnsName'
export JAVA_HOME=/usr/java/default
        """, input
        }
        
        mockTomcatEC2Server.demand.ssh {cmd -> assertEquals ". .sapenv; cd ${SpringSourceDmServer.SPRING_SOURCE_DM_SERVER_HOME}; bin/shutdown.sh", cmd}

        mockTomcatEC2Server.demand.ssh {cmd, text ->
            assertEquals "cat > ${SpringSourceDmServer.SPRING_SOURCE_DM_SERVER_HOME}/config/servletContainer.config", cmd
            assertEquals expectedServerDotXml, text
        }

        mockWebApp.demand.updateTomcat {tomcatServer, bucketPrefix -> }

        mockTerracottaTier.demand.addToCatalinaOpts {optionsBuilder -> }
        mockTerracottaTier.demand.prepareClient {EC2Server instance -> }


        mockTomcatEC2Server.demand.ssh {cmd ->
            assertEquals "(. .sapenv ; cd ${SpringSourceDmServer.SPRING_SOURCE_DM_SERVER_HOME}; nohup bin/startup.sh)  < /dev/null > /dev/null 2>&1 &", cmd}

        mockFileBasedTemplate.use {
            mockTomcatEC2Server.use {
                mockMySqlServer.use {

                    mockDatabaseTier.demand.grantAccessToClient {}
                    mockDatabaseTier.demand.getDatabaseServerDnsName {"myPrivateDnsName"}
                    mockDatabaseTier.demand.getMySqlSlavesDnsName { []}


                    mockDatabaseTier.use {
                        mockTerracottaTier.use {
                            mockWebApp.use {
                                SpringSourceDmServer server = new SpringSourceDmServer(makeClusterSpec(), new EC2Server(), new DatabaseTier(), new TerracottaTier(), new WebServerTier())
                                server.startTomcat()
                            }
                        }
                    }
                }
            }
        }
    }

}